/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.HiddenDanger;
import com.koron.hazardsource.mapper.HiddenDangerMapper;
import com.koron.hazardsource.service.impl.HiddenDangerServiceImpl;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.service.api.TempHiddenDangerService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource({ "classpath:flow.properties" })
public class TempHiddenDangerServiceImpl implements TempHiddenDangerService,AfterApprovalService,InitializingBean {
	private final static Logger logger = LoggerFactory.getLogger(TempHiddenDangerServiceImpl.class);

	@Autowired
	private HiddenDangerServiceImpl hiddenDangerService;
	
	@Autowired
	private FlowManagement flowManagement;
	
	@Value("${safe_standard_hd_add}")
	private String templateKey;
	
	@Value("${flow.standard.setCode}")
    private String setCode;
	
	@SuppressWarnings("unchecked")
	@Override
	public MessageBean<?> merge(StaffBean user, List<HiddenDanger> hdList, String title, String note) {
		MessageBean<?> msg = hiddenDangerService.saveDraft(hdList, user);
		try {
			List<String> idList = new ArrayList<String>();
			if(msg.getData() != null){
				idList = (List<String>) msg.getData();
			}else{
				return msg;
			}
			
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
			audit.setId(DefaultIdGenerator.getInstance().generateLongId());
			audit.setTitle(title);
			audit.setDescription(note);
			audit.setInitiatorCode(user.getCode());
			audit.setTarget("TempHiddenDanger");		//临时隐患入库
			audit.setOperation(1);
			audit.setTemplateKey(templateKey);
			audit.setSetCode(setCode);
			audit.setState(1);
			audit.setFlowType(1);
			audit.setFlowName(Immutable.ADD_HIDDEN_DANGER);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
			}
			hiddenDangerService.updateFstatusflag(idList, 1);
			
			List<String> hdIdList = new ArrayList<String>();
			for (HiddenDanger hd : hdList) {
				String hdIdStr = hd.getDerivationids();
				if(StringUtils.isEmpty(hdIdStr)){
					continue;
				}
				String[] idArrat = hdIdStr.split(",");
				for (String id : idArrat) {
					hdIdList.add(id);
				}
			}
			hiddenDangerService.updateDisposalState(hdIdList, 1);
		}catch (Exception e) {
			return msg;
		}
		return msg;	
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void afterPropertiesSet() throws Exception {
		Map map = flowManagement.getHandlers();
		map.put("TempHiddenDanger", this);
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
	@Override
	public void editApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory()){
			HiddenDangerMapper hdMapper=factory.getMapper(HiddenDangerMapper.class);
			List<HiddenDanger> list = hdMapper.queryListById("hidden_danger_history", idList);
			StringBuffer sb = new StringBuffer();
			for (HiddenDanger hd : list) {
				hd.setState(1);
				hd.setFstatusflag(2);
				sb.append(hd.getDerivationids()).append(",");
			}
			//保存危险源
			hiddenDangerService.save(list);
			//修改审批状态
			hiddenDangerService.updateFstatusflag(idList, 2);
			if(sb.length() > 0){
				//临时隐患改为已入库
				sb.delete(sb.length()-1, sb.length());
				String temp = sb.toString();
				String[] idArray = temp.split(",");
				List<String> ids = new ArrayList(idArray.length);
				Collections.addAll(ids, idArray);
				hiddenDangerService.updateDisposalState(ids, 2);
			}
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		
	}

	@Override
	public void discardApproval(Audit audit) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processDiscard(Audit audit) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void reject(Audit audit, List<String> userIdList) {
		// TODO 流程驳回操作
	}

	@Override
	public void passApproval(Integer operation, Audit audit) {
		// TODO 流程提交成功操作
	}
}
